package com.youlei.newgraduateproject.security.filter;

import cn.hutool.core.util.StrUtil;
import com.youlei.newgraduateproject.entity.SysUser;
import com.youlei.newgraduateproject.security.UserDetailServiceImpl;
import com.youlei.newgraduateproject.service.SysUserService;
import com.youlei.newgraduateproject.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author youlei
 * @version 1.0
 * @Date 2021-05-11-9:59
 * @Description 自定义Jwt认证过滤器
 */

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserDetailServiceImpl userDetailsService;
    @Autowired
    private SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt =request.getHeader(jwtUtils.getHeaderName());
        if (StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request,response);
            return;
        }

        Claims claimByToken = jwtUtils.getClaimByToken(jwt);
        if(claimByToken == null){
            throw new JwtException("token 异常");
        }
        if(jwtUtils.isTokenExpired(claimByToken)){
            throw new JwtException("token 已过期");
        }
        //获取用户及权限信息
        String username = claimByToken.getSubject();
        //根据username获取用户的权限信息
        SysUser sysUser = sysUserService.getByUserName(username);
        List<GrantedAuthority> grantedAuthorities = userDetailsService.getUserAuthority(sysUser.getId());
        //将username封装成token,并放入spring security的上下文认证器中
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(username,null,grantedAuthorities);
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request,response);


    }
}
